import axios from 'axios'
import store from '@/store'
import { Notification, MessageBox } from 'element-ui'
import router from '@/router/index.js'
var root = process.env.BASE_ROOT
//  创建axios实例
var instance = axios.create({
  //  请求超过5秒即超时返回错误
  timeout: 5000,
  headers: { 'Content-Type': 'application/json' }
})
//  重新登录
var toLogin = () => {
  //  可能是token过期，清除它
  store.dispatch('UserLogout')
  //  跳转到登录页面
  router.replace({
    path: '/login',
    //  将跳转的路由path作为参数，登录成功后跳转到该路由
    query: { redirect: router.currentRoute.fullPath }
  })
}

//  request拦截器
instance.interceptors.request.use(
  config => {
    //  判断是否存在token，如果存在的话，则每个http header都加上token
    if (store.state.token) {
      config.headers.Authorization = `Bearer ${store.state.token}`
    }
    //  请求之前重新拼装url
    config.url = root + config.url
    return config
  }
)

// response 拦截器
instance.interceptors.response.use(
  response => {
    const code = response.status
    if (code < 200 || code > 300) {
      Notification.error({
        title: response.message
      })
      return Promise.reject(new Error('error'))
    } else {
      return response.data
    }
  },
  error => {
    if (error.response) {
      const code = error.response.status
      if (code >= 400 && code < 500) {
        if (code === 401) {
          if (!sessionStorage.getItem('ss401')) {
            sessionStorage.setItem('ss401', true)
            MessageBox.confirm(
              '登录已失效，请重新登录',
              '系统提示',
              {
                confirmButtonText: '重新登录',
                cancelButtonText: '取消',
                customClass: 'loginBadWrap',
                type: 'warning'
              }
            ).then(() => {
              sessionStorage.removeItem('ss401')
              //  重新登录
              toLogin()
            }).catch(() => {
              sessionStorage.removeItem('ss401')
            })
          }
        } else if (code === 400) {
          Notification.error({
            title: '错误请求',
            duration: 2500
          })
        } else if (code === 403) {
          Notification.error({
            title: '请求被拒绝',
            duration: 2500
          })
        } else if (code === 404) {
          //  跳转到404页面
          router.replace({
            path: '/404'
          })
        }
      } else if (code >= 500 && code < 600) {
        if (code === 503) {
          Notification.error({
            title: '访问超时',
            duration: 2500
          })
        }
      } else {
        Notification.error({
          title: 'undefined',
          duration: 2500
        })
      }
    }
    return Promise.reject(error)
  }
)
export default instance
